package com.first.module.acm.action;

import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;

import com.first.core.common.QueryFilter;
import com.first.core.util.AppUtil;
import com.first.core.util.PagingBean;
import com.first.core.web.action.BaseAction;
import com.first.module.acm.model.Department;
import com.first.module.acm.service.AppUserService;
import com.first.module.acm.service.DepartmentService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class DepartmentAction extends BaseAction
{

    private Department department;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private AppUserService appUserService;
    
    public DepartmentAction()
    {
    }

    public Department getDepartment()
    {
        return department;
    }

    public void setDepartment(Department department)
    {
        this.department = department;
    }

    public String select()
    {
        String depId = getRequest().getParameter("depId");
        QueryFilter filter = new QueryFilter(getRequest());
        if(StringUtils.isNotEmpty(depId) && !"0".equals(depId))
        {
            department = (Department)departmentService.get(depId);
            filter.addFilter("Q_path_S_LFK", department.getPath());
        }
        filter.addSorted("path", "asc");
        List<Department> list = departmentService.getAll(filter);
        java.lang.reflect.Type type = new TypeToken<List<Department>>(){}.getType();
        StringBuffer buff = (new StringBuffer("{success:true,'totalCounts':")).append(filter.getPagingBean().getTotalItems()).append(",result:");
        Gson gson = (new GsonBuilder()).excludeFieldsWithoutExposeAnnotation().create();
        buff.append(gson.toJson(list, type));
        buff.append("}");
        jsonString = buff.toString();
        return "success";
    }

    public String list()
    {
        String opt = getRequest().getParameter("opt");
        StringBuffer buff = new StringBuffer();
        if(StringUtils.isNotEmpty(opt))
        {
            buff.append("[");
        } else
        {
            buff.append((new StringBuilder("[{id:'0',text:'")).append(AppUtil.getCompanyName()).append("',expanded:true,children:[").toString());
        }
        List listParent = departmentService.findByParentId("0");
        Department dep;
        for(Iterator iterator = listParent.iterator(); iterator.hasNext(); buff.append(findChild(dep.getDepId())))
        {
            dep = (Department)iterator.next();
            buff.append((new StringBuilder("{id:'")).append(dep.getDepId()).append("',text:'").append(dep.getDepName()).append("',").toString());
        }

        if(!listParent.isEmpty())
        {
            buff.deleteCharAt(buff.length() - 1);
        }
        if(StringUtils.isNotEmpty(opt))
        {
            buff.append("]");
        } else
        {
            buff.append("]}]");
        }
        setJsonString(buff.toString());
        return "success";
    }

    public String findChild(String depId)
    {
        StringBuffer buff1 = new StringBuffer("");
        List list = departmentService.findByParentId(depId);
        if(list.size() == 0)
        {
            buff1.append("leaf:true},");
            return buff1.toString();
        }
        buff1.append("children:[");
        Department dep2;
        for(Iterator iterator = list.iterator(); iterator.hasNext(); buff1.append(findChild(dep2.getDepId())))
        {
            dep2 = (Department)iterator.next();
            buff1.append((new StringBuilder("{id:'")).append(dep2.getDepId()).append("',text:'").append(dep2.getDepName()).append("',").toString());
        }

        buff1.deleteCharAt(buff1.length() - 1);
        buff1.append("]},");
        return buff1.toString();
    }

    public String add()
    {
    	String parentId = department.getParentId();
        String depPath = "";
        int level = 0;
        if(parentId.equals(""))
        {
            parentId ="0";
            depPath = "0.";
        } else
        {
            depPath = ((Department)departmentService.get(parentId)).getPath();
            level = ((Department)departmentService.get(parentId)).getDepLevel().intValue();
        }
        if(level < 1)
        {
            level = 1;
        }
        department.setDepLevel(Integer.valueOf(level + 1));
        departmentService.save(department);
        if(department != null)
        {
            depPath = (new StringBuilder(String.valueOf(depPath))).append(department.getDepId().toString()).append(".").toString();
            department.setPath(depPath);
            departmentService.save(department);
            setJsonString("{success:true}");
        } else
        {
            setJsonString("{success:false}");
        }
        return "success";
    }

    public String remove()
    {
        PagingBean pb = getInitPagingBean();
        String depId = getRequest().getParameter("depId");
        Department department = (Department)departmentService.get(depId);
        List userList = appUserService.findByDepartment(department.getPath(), pb);
        if(userList.size() > 0)
        {
            setJsonString("{success:false,message:'\u8BE5\u90E8\u95E8\u8FD8\u6709\u4EBA\u5458\uFF0C\u8BF7\u5C06" +
"\u4EBA\u5458\u8F6C\u79FB\u540E\u518D\u5220\u9664\u90E8\u95E8!'}"
);
            return "success";
        }
        departmentService.remove(depId);
        List list = departmentService.findByParentId(depId);
        Department dep;
        for(Iterator iterator = list.iterator(); iterator.hasNext(); departmentService.remove(dep.getDepId()))
        {
            dep = (Department)iterator.next();
            List users = appUserService.findByDepartment(dep.getPath(), pb);
            if(users.size() > 0)
            {
                setJsonString("{success:false,message:'\u8BE5\u90E8\u95E8\u8FD8\u6709\u4EBA\u5458\uFF0C\u8BF7\u5C06" +
"\u4EBA\u5458\u8F6C\u79FB\u540E\u518D\u5220\u9664\u90E8\u95E8!'}"
);
                return "success";
            }
        }

        setJsonString("{success:true}");
        return "success";
    }

    public String detail()
    {
    	String depId = getRequest().getParameter("depId");
        setDepartment((Department)departmentService.get(depId));
        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer("{success:true,data:[");
        sb.append(gson.toJson(department));
        sb.append("]}");
        setJsonString(sb.toString());
        return "success";
    }
}
